<template>
  <div class="p-2">
    <transition :enter-active-class="proxy?.animate.searchAnimate.enter" :leave-active-class="proxy?.animate.searchAnimate.leave">
      <div v-show="showSearch" class="mb-[10px]">
        <el-card shadow="hover">
          <el-form ref="queryFormRef" :model="queryParams" :inline="true">
            <el-form-item label="保险类型" prop="categoryName">
              <el-select v-model="queryParams.categoryName" placeholder="请输入保险类型">
                <el-option v-for="category in CategoryOptions" :key="category.categoryName" :label="category.categoryName" :value="category.categoryName"  />
              </el-select>
            </el-form-item>
            <el-form-item>
              <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
              <el-button icon="Refresh" @click="resetQuery">重置</el-button>
            </el-form-item>
          </el-form>
        </el-card>
      </div>
    </transition>

    <el-card shadow="never">
      <template #header>
        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button type="primary" plain icon="Plus" @click="handleAdd" v-hasPermi="['Nyt7InsuranceProduct:Nyt7InsuranceProduct:add']">新增</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="success" plain icon="Edit" :disabled="single" @click="handleUpdate()" v-hasPermi="['Nyt7InsuranceProduct:Nyt7InsuranceProduct:edit']">修改</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="danger" plain icon="Delete" :disabled="multiple" @click="handleDelete()" v-hasPermi="['Nyt7InsuranceProduct:Nyt7InsuranceProduct:remove']">删除</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="warning" plain icon="Download" @click="handleExport" v-hasPermi="['Nyt7InsuranceProduct:Nyt7InsuranceProduct:export']">导出</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="warning" plain icon="Upload" @click="handleImport" v-hasPermi="['Nyt7InsuranceProduct:Nyt7InsuranceProduct:export']"
            >导入</el-button
            >
          </el-col>
          <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
        </el-row>
      </template>

      <el-table v-loading="loading" :data="Nyt7InsuranceProductList" @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column label="" align="center" prop="id" v-if="false" />
        <el-table-column label="序号" align="center">
          <template #default="scope">
            {{ (queryParams.pageNum - 1) * queryParams.pageSize + scope.$index + 1 }}
          </template>
        </el-table-column>
        <el-table-column label="产品名称" align="center" prop="productName" />
        <el-table-column label="保险类型" align="center" prop="categoryName" />
        <el-table-column label="保险公司名称" align="center" prop="companyName" />

        <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
          <template #default="scope">
            <el-tooltip content="详情" placement="top">
              <el-button link type="primary" icon="View" @click="handleView(scope.row)" v-hasPermi="['Nyt7InsuranceProduct:Nyt7InsuranceProduct:edit']"></el-button>
            </el-tooltip>
            <el-tooltip content="修改" placement="top">
              <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)" v-hasPermi="['Nyt7InsuranceProduct:Nyt7InsuranceProduct:edit']"></el-button>
            </el-tooltip>
            <el-tooltip content="删除" placement="top">
              <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)" v-hasPermi="['Nyt7InsuranceProduct:Nyt7InsuranceProduct:remove']"></el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>

      <pagination v-show="total > 0" :total="total" v-model:page="queryParams.pageNum" v-model:limit="queryParams.pageSize" @pagination="getList" />
    </el-card>
    <!--数据导入对话框 -->
    <el-dialog title="数据导入" v-model="excelOpen" width="400px" append-to-body>
      <el-upload
        ref="uploadRef"
        class="upload-demo"
        :auto-upload="false"
        :on-change="handleChange"
        :limit="1"
        accept=".xlsx,.xls">
        <template #trigger>
          <el-button type="primary">选择文件</el-button>
        </template>
        <el-button class="ml-3" type="success" @click="submitUpload">上传</el-button>
        <template #tip>
          <el-button class="ml-3" type="success" @click="handleExportTemplate">下载导入模版</el-button>
          <div class="el-upload__tip">上传文件仅支持，xls/xlsx格式，文件大小不得超过20M</div>
        </template>
      </el-upload>
    </el-dialog>
    <!-- 添加或修改保险产品对话框 -->
    <el-dialog :title="dialog1.title" v-model="dialog1.visible" width="800px" append-to-body>
      <el-form ref="Nyt7InsuranceProductFormRef" :model="form" :rules="rules" label-width="110px">
        <el-card class="mb-4">
          <template #header>
            <div class="card-header">
              <span class="title">产品基本信息</span>
            </div>
          </template>

          <el-row :gutter="20">
              <el-col :span="12">
            <el-form-item label="保险公司名称" prop="companyName">
              <el-select v-model="form.companyName" placeholder="请输入保险公司名称">
                <el-option v-for="postName in postOptions" :key="postName.postName" :label="postName.postName" :value="postName.postName" />
              </el-select>
            </el-form-item>
              </el-col> <el-col :span="12">

        <el-form-item label="保险类型" prop="categoryName">
          <el-select v-model="form.categoryName" placeholder="请输入保险类型">
            <el-option v-for="category in CategoryOptions" :key="category.categoryName" :label="category.categoryName" :value="category.categoryName" />
          </el-select>
        </el-form-item>
          </el-col> <el-col :span="12">

        <el-form-item label="产品名称" prop="productName">
          <el-input v-model="form.productName" placeholder="请输入产品名称" />
        </el-form-item>
          </el-col> <el-col :span="12">

        <el-form-item label="保险期限" prop="insuranceDuration">
          <el-input v-model="form.insuranceDuration" placeholder="请输入保险期限" />
        </el-form-item>
          </el-col> <el-col :span="12">

        <el-form-item label="单位保费" prop="unitPremium">
          <el-input v-model="form.unitPremium" placeholder="请输入单位保费" />
        </el-form-item>
          </el-col> <el-col :span="12">

        <el-form-item label="投保单位" prop="insureUnit">
          <el-input v-model="form.insureUnit" placeholder="请输入投保单位" />
        </el-form-item>
          </el-col> <el-col :span="12">

        <el-form-item label="单位保额" prop="unitAmount">
          <el-input v-model="form.unitAmount" placeholder="请输入单位保额" />
        </el-form-item>

          </el-col> <el-col :span="12">

            <el-form-item label="产品简介" prop="productIntroduction">

              <el-input v-model="form.productIntroduction" type="textarea" placeholder="请输入内容" />
            </el-form-item>
          </el-col>
          </el-row>
        </el-card>
            <el-card class="mb-4">
              <template #header>
                <div class="card-header">
                  <span class="title">各级财政补贴金额数据</span>
                </div>
              </template>

              <el-row :gutter="20">
                <el-col :span="12">
        <el-form-item label="中央财政补贴" prop="ratioCentralFiscalSubsidy">
          <el-input v-model="form.ratioCentralFiscalSubsidy" placeholder="请输入中央财政补贴" />
        </el-form-item>
                </el-col> <el-col :span="12">

        <el-form-item label="省级财政补贴" prop="ratioProvincialFiscalSubsidy">
          <el-input v-model="form.ratioProvincialFiscalSubsidy" placeholder="请输入省级财政补贴" />
        </el-form-item>
              </el-col> <el-col :span="12">

        <el-form-item label="地市财政补贴" prop="ratioMunicipalFiscalSubsidy">
          <el-input v-model="form.ratioMunicipalFiscalSubsidy" placeholder="请输入地市财政补贴" />
        </el-form-item>
              </el-col> <el-col :span="12">

        <el-form-item label="区县财政补贴" prop="ratioDistrictAndCountyFiscalSubsidy">
          <el-input v-model="form.ratioDistrictAndCountyFiscalSubsidy" placeholder="请输入区县财政补贴" />
        </el-form-item>
              </el-col> <el-col :span="12">

        <el-form-item label="其他财政补贴" prop="ratioOtherFiscalSubsidies">
          <el-input v-model="form.ratioOtherFiscalSubsidies" placeholder="请输入其他财政补贴" />
        </el-form-item>
              </el-col>
              </el-row>
        </el-card>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button :loading="buttonLoading" type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>

    <el-dialog :title="dialog2.title" v-model="dialog2.visible" width="800px" append-to-body>
      <el-form ref="Nyt7InsuranceProductFormRef" :model="form2" label-width="110px">
        <el-card class="mb-4">
          <template #header>
            <div class="card-header">
              <span class="title">产品基本信息</span>
            </div>
          </template>
          <el-descriptions :column="2" border>
              <el-descriptions-item label="保险公司名称" prop="companyName">
                {{ form2.companyName }}
              </el-descriptions-item>

              <el-descriptions-item label="保险类型" prop="categoryName">
                {{ form2.categoryName }}
              </el-descriptions-item>


              <el-descriptions-item label="产品名称" prop="productName">
                {{ form2.productName }}
              </el-descriptions-item>


              <el-descriptions-item label="保险期限" prop="insuranceDuration">
                {{ form2.insuranceDuration }}
              </el-descriptions-item>


              <el-descriptions-item label="单位保费" prop="unitPremium">
                {{ form2.unitPremium }}
              </el-descriptions-item>


              <el-descriptions-item label="投保单位" prop="insureUnit">
                {{ form2.insureUnit }}
              </el-descriptions-item>


              <el-descriptions-item label="单位保额" prop="unitAmount">
                {{ form2.unitAmount }}
              </el-descriptions-item>


              <el-descriptions-item label="产品简介" prop="productIntroduction">
                <div v-html="form2.productIntroduction" style="border: 1px solid #ccc; padding: 10px; border-radius: 4px; width: 100%"></div>
              </el-descriptions-item>
          </el-descriptions>
        </el-card>
        <el-card class="mb-4">
          <template #header>
            <div class="card-header">
              <span class="title">财政补贴信息</span>
            </div>
          </template>

          <el-descriptions :column="2" border>
              <el-descriptions-item label="中央财政补贴" label-width="150px" prop="ratioCentralFiscalSubsidy">
                {{ form2.ratioCentralFiscalSubsidy }}
              </el-descriptions-item>


              <el-descriptions-item label="省级财政补贴" label-width="150px" prop="ratioProvincialFiscalSubsidy">
                {{ form2.ratioProvincialFiscalSubsidy }}
              </el-descriptions-item>


              <el-descriptions-item label="地市财政补贴" label-width="150px" prop="ratioMunicipalFiscalSubsidy">
                {{ form2.ratioMunicipalFiscalSubsidy }}
              </el-descriptions-item>


              <el-descriptions-item label="区县财政补贴" label-width="150px" prop="ratioDistrictAndCountyFiscalSubsidy">
                {{ form2.ratioDistrictAndCountyFiscalSubsidy }}
              </el-descriptions-item>


              <el-descriptions-item label="其他财政补贴" label-width="150px" prop="ratioOtherFiscalSubsidies">
                {{ form2.ratioOtherFiscalSubsidies }}
              </el-descriptions-item>
          </el-descriptions>
        </el-card>
        <el-card class="mb-4">
          <template #header>
            <div class="card-header">
              <span class="title">其它信息</span>
            </div>
          </template>
          <el-descriptions :column="1" border>
            <el-descriptions-item label="适用人群" prop="suitableFor">
              {{ form2.suitableFor }}
            </el-descriptions-item>
            <el-descriptions-item label="保障范围" prop="coverage">
              <div v-html="form2.coverage" style="border: 1px solid #ccc; padding: 10px; border-radius: 4px; width: 100%"></div>
            </el-descriptions-item>
            <el-descriptions-item label="省" prop="province">
              {{ form2.province }}
            </el-descriptions-item>
            <el-descriptions-item label="市" prop="city">
              {{ form2.city }}
            </el-descriptions-item>
            <el-descriptions-item label="区" prop="district">
              {{ form2.district }}
            </el-descriptions-item>
            <el-descriptions-item label="补贴比例" prop="subsidyRatio">
              {{ form2.subsidyRatio }}
            </el-descriptions-item>
            <el-descriptions-item label="保险责任" prop="insuranceLiability">
              <div v-html="form2.insuranceLiability" style="border: 1px solid #ccc; padding: 10px; border-radius: 4px; width: 100%"></div>
            </el-descriptions-item>
            <el-descriptions-item label="投保要求" prop="requirements">
              <div v-html="form2.requirements" style="border: 1px solid #ccc; padding: 10px; border-radius: 4px; width: 100%"></div>
            </el-descriptions-item>
            <el-descriptions-item label="理赔流程" prop="claimsProcess">
              <div v-html="form2.claimsProcess" style="border: 1px solid #ccc; padding: 10px; border-radius: 4px; width: 100%"></div>
            </el-descriptions-item>
            <el-descriptions-item label="预约份数" prop="numberReservations">
              {{ form2.numberReservations }}
            </el-descriptions-item>
            <el-descriptions-item label="是否为创新产品" prop="innovativeProducts">
              {{ form2.innovativeProducts }}
            </el-descriptions-item>
            <el-descriptions-item label="申请日期" prop="dateApplication">
              {{ form2.dateApplication }}
            </el-descriptions-item>
            <el-descriptions-item label="上架日期" prop="listingDate">
              {{ form2.listingDate }}
            </el-descriptions-item>
            <el-descriptions-item label="状态" prop="state">
              {{ form2.state }}
            </el-descriptions-item>
          </el-descriptions>
        </el-card>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="cancel">返 回</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="Nyt7InsuranceProduct" lang="ts">
import { listNyt7InsuranceProduct, getNyt7InsuranceProduct, delNyt7InsuranceProduct, addNyt7InsuranceProduct, updateNyt7InsuranceProduct , exportSelected} from '@/api/Nyt7InsuranceProduct/Nyt7InsuranceProduct';
import {
  Nyt7InsuranceProductVO,
  Nyt7InsuranceProductQuery,
  Nyt7InsuranceProductForm,
  Nyt7InsuranceProduct
} from '@/api/Nyt7InsuranceProduct/Nyt7InsuranceProduct/types';
import { PostVO } from '@/api/system/post/types';
import { listPost } from '@/api/system/post';
import { listNyt7InsuranceCategory } from '@/api/Nyt7InsuranceCategory/Nyt7InsuranceCategory';
import { Nyt7InsuranceCategoryVO } from '@/api/Nyt7InsuranceCategory/Nyt7InsuranceCategory/types';
import { importExcel } from '@/api/Nyt7InsuranceProduct/Nyt7InsuranceProduct';

const { proxy } = getCurrentInstance() as ComponentInternalInstance;

const Nyt7InsuranceProductList = ref<Nyt7InsuranceProductVO[]>([]);
const buttonLoading = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref<Array<string | number>>([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);

const queryFormRef = ref<ElFormInstance>();
const Nyt7InsuranceProductFormRef = ref<ElFormInstance>();

const dialog1 = reactive<DialogOption>({
  visible: false,
  title: ''
});
const dialog2 = reactive<DialogOption>({
  visible: false,
  title: ''
});

const initFormData2: Nyt7InsuranceProduct = {
  id: 0,
  city: '',
  claimsProcess: '',
  coverage: '',
  dateApplication: undefined,
  district: '',
  innovativeProducts: '',
  insuranceLiability: '',
  listingDate: undefined,
  numberReservations: '',
  province: '',
  requirements: '',
  state: '',
  subsidyRatio: '',
  suitableFor: '',

  companyName: undefined,
  categoryName: undefined,
  productName: undefined,
  productIntroduction: undefined,
  insuranceDuration: undefined,
  unitPremium: undefined,
  insureUnit: undefined,
  unitAmount: undefined,
  ratioCentralFiscalSubsidy: undefined,
  ratioProvincialFiscalSubsidy: undefined,
  ratioMunicipalFiscalSubsidy: undefined,
  ratioDistrictAndCountyFiscalSubsidy: undefined,
  ratioOtherFiscalSubsidies: undefined
}
const data2 = reactive<PageData<Nyt7InsuranceProduct, Nyt7InsuranceProductQuery>>({
  form: { ...initFormData2 }
});

const initFormData: Nyt7InsuranceProductForm = {
  companyName: undefined,
  categoryName: undefined,
  productName: undefined,
  productIntroduction: undefined,
  insuranceDuration: undefined,
  unitPremium: undefined,
  insureUnit: undefined,
  unitAmount: undefined,
  ratioCentralFiscalSubsidy: undefined,
  ratioProvincialFiscalSubsidy: undefined,
  ratioMunicipalFiscalSubsidy: undefined,
  ratioDistrictAndCountyFiscalSubsidy: undefined,
  ratioOtherFiscalSubsidies: undefined,
}
const data = reactive<PageData<Nyt7InsuranceProductForm, Nyt7InsuranceProductQuery>>({
  form: {...initFormData},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    categoryName: undefined,
    params: {
    }
  },
  rules: {
    companyName: [
      { required: true, message: "保险公司名称不能为空", trigger: "change" }
    ],
    categoryName: [
      { required: true, message: "保险类型不能为空", trigger: "blur" }
    ],
    productName: [
      { required: true, message: "产品名称不能为空", trigger: "blur" }
    ],
    productIntroduction: [
      { required: true, message: "产品简介不能为空", trigger: "blur" }
    ],
    insuranceDuration: [
      { required: true, message: "保险期限不能为空", trigger: "blur" }
    ],
    unitPremium: [
      { required: true, message: "单位保费不能为空", trigger: "blur" }
    ],
    insureUnit: [
      { required: true, message: "投保单位不能为空", trigger: "blur" }
    ],
    unitAmount: [
      { required: true, message: "单位保额不能为空", trigger: "blur" }
    ],
    ratioCentralFiscalSubsidy: [
      { required: true, message: "中央财政补贴不能为空", trigger: "blur" }
    ],
    ratioProvincialFiscalSubsidy: [
      { required: true, message: "省级财政补贴不能为空", trigger: "blur" }
    ],
    ratioMunicipalFiscalSubsidy: [
      { required: true, message: "地市财政补贴不能为空", trigger: "blur" }
    ],
    ratioDistrictAndCountyFiscalSubsidy: [
      { required: true, message: "区县财政补贴不能为空", trigger: "blur" }
    ],
    ratioOtherFiscalSubsidies: [
      { required: true, message: "其他财政补贴不能为空", trigger: "blur" }
    ],
  }
});

const { queryParams, form, rules } = toRefs(data);

const { form: form2 } = toRefs(data2);

/** 查询保险产品列表 */
const getList = async () => {
  loading.value = true;
  const res = await listNyt7InsuranceProduct(queryParams.value);
  Nyt7InsuranceProductList.value = res.rows;
  total.value = res.total;
  loading.value = false;
}

/** 取消按钮 */
const cancel = () => {
  reset();
  dialog1.visible = false;
  dialog2.visible = false;
}

/** 表单重置 */
const reset = () => {
  form.value = {...initFormData};
  Nyt7InsuranceProductFormRef.value?.resetFields();
}

/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.value.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
const resetQuery = () => {
  queryFormRef.value?.resetFields();
  handleQuery();
}




// /** 多选框选中数据 */
// const handleSelectionChange = (selection: Nyt7InsuranceProductVO[]) => {
//   ids.value = selection.map(item => item.id);
//   single.value = selection.length != 1;
//   multiple.value = !selection.length;
// }
const handleSelectionChange = (selection: Nyt7InsuranceProductVO[]) => {
  ids.value = selection.map(item => item.id);
  selectedRows.value = selection; // 存储选中的数据行
  single.value = selection.length !== 1;
  multiple.value = selection.length === 0;
}

/** 新增按钮操作 */
const handleAdd = () => {
  reset();
  dialog1.visible = true;
  dialog1.title = "添加保险产品";
}

/** 修改按钮操作 */
const handleUpdate = async (row?: Nyt7InsuranceProductVO) => {
  reset();
  const _id = row?.id || ids.value[0]
  const res = await getNyt7InsuranceProduct(_id);
  Object.assign(form.value, res.data);
  dialog1.visible = true;
  dialog1.title = "修改保险产品";
}

/** 详情按钮操作 */
const handleView = async (row?: Nyt7InsuranceProductVO) => {
  reset();
  const _id = row?.id || ids.value[0]
  const res = await getNyt7InsuranceProduct(_id);
  Object.assign(form2.value, res.data);
  dialog2.visible = true;
  dialog2.title = "保险产品详情";
}

/** 提交按钮 */
const submitForm = () => {
  Nyt7InsuranceProductFormRef.value?.validate(async (valid: boolean) => {
    if (valid) {
      buttonLoading.value = true;
      console.log(form.value);
      if (form.value.id) {
        await updateNyt7InsuranceProduct(form.value).finally(() =>  buttonLoading.value = false);
      } else {
        await addNyt7InsuranceProduct(form.value).finally(() =>  buttonLoading.value = false);
      }
      proxy?.$modal.msgSuccess("操作成功");
      dialog1.visible = false;
      await getList();
    }
  });
}

/** 删除按钮操作 */
const handleDelete = async (row?: Nyt7InsuranceProductVO) => {
  const _ids = row?.id || ids.value;
  await proxy?.$modal.confirm('是否确认删除保险产品编号为"' + _ids + '"的数据项？').finally(() => loading.value = false);
  await delNyt7InsuranceProduct(_ids);
  proxy?.$modal.msgSuccess("删除成功");
  await getList();
}

// /** 导出按钮操作 */
// const handleExport = () => {
//   proxy?.download('Nyt7InsuranceProduct/Nyt7InsuranceProduct/export', {
//     ...queryParams.value
//   }, `Nyt7InsuranceProduct_${new Date().getTime()}.xlsx`)
// }

const selectedRows = ref<Nyt7InsuranceProductVO[]>([]);





// const handleExport = () => {
//   if (selectedRows.value.length > 0) {
//     // 导出选中的数据
//     exportSelectedRows(selectedRows.value);
//   } else {
//     // 导出所有数据
//     proxy?.download('Nyt7InsuranceProduct/Nyt7InsuranceProduct/export', {
//       ...queryParams.value
//     }, `Nyt7InsuranceProduct_${new Date().getTime()}.xlsx`);
//   }
// }

// const exportSelectedRows = async (rows: Nyt7InsuranceProductVO[]) => {
//   try {
//     const response = await exportSelected(rows.map(row => row.id));
//     const url = window.URL.createObjectURL(new Blob([response]));
//     const link = document.createElement('a');
//     link.href = url;
//     link.setAttribute('download', `Nyt7InsuranceProduct_${new Date().getTime()}.xlsx`);
//     document.body.appendChild(link);
//     link.click();
//   } catch (error) {
//     console.error('导出选中的数据失败:', error);
//     proxy?.$modal.msgError('导出选中的数据失败');
//   }
// }


const exportSelectedRows = async (rows: Nyt7InsuranceProductVO[]) => {
  try {
    // 输出要导出的数据列表，便于调试
    console.log('开始导出选中的数据:', rows);

    // 提取选中的数据的ID列表
    const ids = rows.map(row => row.id);
    // 输出提取的ID列表，便于调试
    console.log('选中的数据ID列表:', ids);

    // 调用API导出选中的数据
    const response = await exportSelected(ids);
    // 输出API响应，便于调试
    console.log('导出响应:', response);

    // 创建一个Blob对象，用于创建下载链接
    const url = window.URL.createObjectURL(new Blob([response]));
    // 输出创建的URL，便于调试
    console.log('创建的URL:', url);

    // 创建一个<a>元素，用于触发文件下载
    const link = document.createElement('a');
    // 设置下载链接的href属性
    link.href = url;
    // 设置下载文件的名称
    link.setAttribute('download', `Nyt7InsuranceProduct_${new Date().getTime()}.xlsx`);
    // 输出创建的下载链接，便于调试
    console.log('创建的下载链接:', link);

    // 将<a>元素添加到文档中
    document.body.appendChild(link);
    // 触发点击事件，开始下载文件
    link.click();
    // 输出下载链接点击完成的信息，便于调试
    console.log('下载链接点击完成');

    // 移除<a>元素，清理DOM
    document.body.removeChild(link);
  } catch (error) {
    // 捕获并输出错误信息，便于调试
    console.error('导出选中的数据失败:', error);
    // 显示错误提示给用户
    proxy?.$modal.msgError('导出选中的数据失败');
  }
}


const handleExport = () => {
  if (selectedRows.value.length > 0) {
    // 输出选中的行数据，便于调试
    console.log('选中的行数据:', selectedRows.value);
    // 导出选中的数据
    exportSelectedRows(selectedRows.value);
  } else {
    // 输出查询参数，便于调试
    console.log('查询参数:', queryParams.value);
    // 导出所有数据
    proxy?.download('Nyt7InsuranceProduct/Nyt7InsuranceProduct/export', {
      ...queryParams.value
    }, `Nyt7InsuranceProduct_${new Date().getTime()}.xlsx`);
  }
}

















const postList = ref<PostVO[]>([]);
const postOptions = ref<PostVO[]>([]);

//获取保险公司数据
const getPostList = async () => {
  const res = await listPost();
  postList.value = res.rows;
  postOptions.value = postList.value;
  console.log(res);
  console.log(postList);
};

const CategoryList = ref<Nyt7InsuranceCategoryVO[]>([]);
const CategoryOptions = ref<Nyt7InsuranceCategoryVO[]>([]);

//获取保险产品类型数据
const getCategoryList = async () => {
  const res = await listNyt7InsuranceCategory();
  CategoryList.value = res.data;
  console.log('category,res');
  console.log(CategoryList);
  CategoryOptions.value = CategoryList.value.filter(item => item.parentId == '0');
  console.log('category,res');
  console.log(res);
  console.log(CategoryOptions.value);
};
// //处理市的选择变化
// const handleCityChange = (cityName: string) => {
//   const selectedCity = cityOptions.value.find(city => city.regionName === cityName);
//   if (selectedCity) {
//     countyOptions.value = regionManagementList.value.filter(item => item.parentId === selectedCity.regionId);
//   } else {
//     countyOptions.value = [];
//   }
// };

/* 打开数据导入的对话框 */
const excelOpen = ref(false);

function handleImport() {
  excelOpen.value = true;
}

// 存储选择的文件
const selectedFile = ref(null);

// 文件选择变化时的处理
const handleChange = (file) => {
  selectedFile.value = file.raw;
};

// 提交上传
const submitUpload = async () => {
  if (!selectedFile.value) {
    proxy?.$modal.msgError('请先选择文件');
    return;
  }

  try {
    proxy?.$modal.loading('正在上传excel，请稍候...');
    const res = await importExcel(selectedFile.value);
    if (res.code === 200) {
      proxy?.$modal.msgSuccess('上传excel成功');
      excelOpen.value = false;
      getList();
    } else {
      proxy?.$modal.msgError(res.msg);
    }
  } catch (error) {
    proxy?.$modal.msgError('上传excel失败');
  } finally {
    proxy.$modal.closeLoading();
    uploadRef.value.clearFiles();
  }

};

/** 下载导入模版 */
const handleExportTemplate = () =>{
  proxy?.download(
    'Nyt7InsuranceProduct/Nyt7InsuranceProduct/template',
    {},
    `保险产品信息导入模版.xlsx`
  )
}

onMounted(() => {
  getList();
  getPostList();
  getCategoryList();
});
</script>
